﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MauiBuilder.Behaviors;

public class RadioButtonCommandBehavior : Behavior<RadioButton>
{
    public static readonly BindableProperty CommandProperty =
        BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(RadioButtonCommandBehavior));

    public static readonly BindableProperty CommandParameterProperty =
        BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(RadioButtonCommandBehavior));

    public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public object CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }

    protected override void OnAttachedTo(RadioButton radioButton)
    {
        base.OnAttachedTo(radioButton);
        radioButton.CheckedChanged += OnCheckedChanged;
    }

    protected override void OnDetachingFrom(RadioButton radioButton)
    {
        radioButton.CheckedChanged -= OnCheckedChanged;
        base.OnDetachingFrom(radioButton);
    }

    private void OnCheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        if (e.Value && Command?.CanExecute(CommandParameter) == true)
        {
            Command.Execute(CommandParameter);
        }
    }
}
